package com.qing.demo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class NettyClient {
    public static void main(String[] args) {
        new NettyClient().connect("127.0.0.1",7379);
    }

    private void connect(String host,int port){
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioDatagramChannel.class);
            bootstrap.handler(new MyChannelInitializer());

            Channel channel = bootstrap.bind(7378).sync().channel();
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("hello world", Charset.forName("utf-8")),new InetSocketAddress(host,port))).sync();
            channel.closeFuture().await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
}
